package cn.rocky.prepare;

public class reorderSpaces {

    public static String reorderSpaces(String text) {
        int length = text.length();
        String[] words = text.trim().split("\\s+");
        int cntSpace = length;
        for (String word : words) {
            cntSpace -= word.length();
        }
        StringBuilder sb = new StringBuilder();
        int len = words.length;
        if (len == 1) {
            sb.append(words[0]);
            doCreateBlank(sb, cntSpace);
            return sb.toString();
        }
        int perSpace = cntSpace / (len - 1); // 中间
        int restSpace = cntSpace % (len - 1);// 最后
        for (int i = 0; i < len; i++) {
            if (i > 0) {
                doCreateBlank(sb, perSpace);
            }
            sb.append(words[i]);
        }
        doCreateBlank(sb, restSpace);
        return sb.toString();
    }

    private static void doCreateBlank(StringBuilder sb, int restSpace) {
        for (int i = 0; i < restSpace; i++) {
            sb.append(' ');
        }
    }

    public static void main(String[] args) {
        String text = " practice   makes   perfect";
        System.out.println(reorderSpaces(text));
    }
}
